import React, { useState, useEffect } from 'react';
import { http, API_PATH } from '../utils/http';

// 素材状态类型
type MaterialStatus = 'pending' | 'completed' | 'processing' | 'failed';

// 状态常量
const MATERIAL_STATUS = {
    PENDING: 'pending',     // 待处理
    COMPLETED: 'completed', // 已完成
    PROCESSING: 'processing', // 处理中
    FAILED: 'failed'        // 处理失败
} as const;

// 状态对应的文字描述
const statusTextMap: Record<MaterialStatus, string> = {
    pending: '待处理',
    completed: '已完成',
    processing: '处理中',
    failed: '处理失败'
};

// 状态对应的颜色
const statusColorMap: Record<MaterialStatus, string> = {
    pending: 'bg-indigo-50 text-indigo-600 border border-indigo-200',
    completed: 'bg-emerald-50 text-emerald-600 border border-emerald-200',
    processing: 'bg-sky-50 text-sky-600 border border-sky-200',
    failed: 'bg-rose-50 text-rose-600 border border-rose-200'
};

// 素材表单接口
interface MaterialForm {
    url: string;
    title?: string;
    source: string;
    author?: string;
    tags?: string[];
}

// 素材响应接口
interface MaterialResponse {
    material_id: string;
    job_id: string;
    message: string;
}

// 素材列表项接口
interface MaterialItem {
    id: string;
    url: string;
    title: string;
    source: string;
    author: string;
    read_count: string;
    tags: string[];
    status: MaterialStatus;
    error: string | null;
    created_at: number;
    processed_at: number;
    processing_time: number;
    topic_extracted: boolean;
    user_id?: string;
    display_name?: string;
}

const MaterialCenter: React.FC = () => {
    // 返回首页
    const handleBack = () => {
        window.location.href = '/';
    };

    // 新增素材弹窗可见性
    const [modalVisible, setModalVisible] = useState(false);
    // 表单数据
    const [formData, setFormData] = useState<MaterialForm>({
        url: '',
        title: '',
        source: '',
        author: '',
        tags: []
    });
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 来源选项列表
    const [sourceOptions, setSourceOptions] = useState<string[]>([]);
    // 来源选项加载状态
    const [sourcesLoading, setSourcesLoading] = useState(false);
    // 素材列表
    const [materials, setMaterials] = useState<MaterialItem[]>([]);
    // 当前选中的状态筛选
    const [statusFilter, setStatusFilter] = useState<MaterialStatus | null>(null);
    // 当前选中的来源筛选
    const [sourceFilter, setSourceFilter] = useState<string | null>(null);
    // 分页信息
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    // Toast提示
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info'; visible: boolean }>({
        message: '',
        type: 'info',
        visible: false
    });

    // 提取话题确认弹窗
    const [showExtractConfirm, setShowExtractConfirm] = useState<string | null>(null);
    // 提取话题状态
    const [extracting, setExtracting] = useState<string | null>(null);

    // 获取素材列表
    const fetchMaterials = async (page = pagination.current, pageSize = pagination.pageSize, status: MaterialStatus | null = statusFilter, source: string | null = sourceFilter) => {
        setLoading(true);
        try {
            const params: Record<string, unknown> = {
                page,
                page_size: pageSize
            };

            if (status) {
                params.status = status;
            }

            if (source) {
                params.source = source;
            }

            const response = await http.get<MaterialItem>(API_PATH.MATERIAL.LIST, params);

            response.onSuccess(() => {
                setMaterials(response.list);
                const meta = response.meta;
                if (meta) {
                    setPagination({
                        current: meta.page,
                        pageSize: meta.page_size,
                        total: meta.total
                    });
                }
            }).onError((code, msg) => {
                console.error(`获取列表失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`获取素材列表失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 获取来源列表
    const fetchSourceOptions = async () => {
        setSourcesLoading(true);
        try {
            const response = await http.get<string[]>(API_PATH.MATERIAL.SOURCES);

            // 按照正确方式处理响应
            response.onSuccess((result) => {
                console.log('获取来源列表成功:', result);
                if (response.data == null) {
                    showToast("获取来源失败");
                    return;
                }
                const sources = response.data as string[];

                setSourceOptions(sources);
                // 设置第一个选项为默认值
                if (sources.length > 0) {
                    setFormData(prev => ({ ...prev, source: sources[0] }));
                }
            }).onError((code, msg) => {
                console.error(`获取来源失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`获取来源失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('获取来源网络请求异常:', error);
            showToast('获取来源网络请求异常', 'error');
        } finally {
            setSourcesLoading(false);
        }
    };

    // 页面加载时获取数据
    useEffect(() => {
        fetchSourceOptions();
        fetchMaterials();
    }, []);

    // 处理状态筛选变化
    const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value;
        let newStatus: MaterialStatus | null = null;

        if (value && value !== 'all') {
            newStatus = value as MaterialStatus;
        }

        setStatusFilter(newStatus);
        fetchMaterials(1, pagination.pageSize, newStatus, sourceFilter);
    };

    // 处理来源筛选变化
    const handleSourceChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value;
        let newSource: string | null = null;

        if (value && value !== 'all') {
            newSource = value;
        }

        setSourceFilter(newSource);
        fetchMaterials(1, pagination.pageSize, statusFilter, newSource);
    };

    // 格式化时间
    const formatDate = (timestamp: number) => {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    };

    // 处理爬取/重新爬取
    const handleRetry = async (materialId: string, e: React.MouseEvent) => {
        e.stopPropagation(); // 阻止事件冒泡，避免触发卡片点击导航事件
        setLoading(true);

        try {
            const response = await http.post<MaterialResponse>(
                API_PATH.MATERIAL.RETRY,
                { material_id: materialId } as unknown as Record<string, unknown>
            );

            response.onSuccess(() => {
                showToast('素材爬取任务已加入队列', 'success');
                // 刷新列表
                fetchMaterials();
            }).onError((code, msg) => {
                console.error(`重新爬取失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`重新爬取失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 处理删除素材
    const handleDelete = async (materialId: string, e: React.MouseEvent) => {
        e.stopPropagation(); // 阻止事件冒泡，避免触发卡片点击导航事件

        if (!window.confirm('确定要删除此素材吗？此操作不可撤销。')) {
            return;
        }

        setLoading(true);

        try {
            const response = await http.post<string>(
                API_PATH.MATERIAL.DELETE,
                { material_id: materialId } as unknown as Record<string, unknown>
            );

            response.onSuccess(() => {
                showToast('素材删除成功', 'success');
                // 刷新列表
                fetchMaterials();
            }).onError((code, msg) => {
                console.error(`删除失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`删除失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 处理提取话题
    const handleExtractTopic = async (materialId: string, e: React.MouseEvent) => {
        e.stopPropagation(); // 阻止事件冒泡，避免触发卡片点击导航事件
        const material = materials.find(m => m.id === materialId);
        if (!material) return;

        // 如果已经提取过，显示确认弹窗
        if (material.topic_extracted) {
            setShowExtractConfirm(materialId);
            return;
        }

        await doExtractTopic(materialId);
    };

    // 执行提取话题
    const doExtractTopic = async (materialId: string) => {
        setExtracting(materialId);
        try {
            const response = await http.post<{
                material_id: string;
                topic: string;
                job_id: string;
                articles_count: number;
            }>(
                '/v1/material/extract-topic',
                { material_id: materialId } as unknown as Record<string, unknown>
            );

            response.onSuccess(() => {
                showToast('话题提取任务已提交', 'success');
                // 更新本地状态
                setMaterials(prev => prev.map(m =>
                    m.id === materialId
                        ? { ...m, topic_extracted: true }
                        : m
                ));
            }).onError((code, msg) => {
                console.error(`提取话题失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`提取话题失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setExtracting(null);
            setShowExtractConfirm(null);
        }
    };

    // 显示Toast
    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type, visible: true });
        setTimeout(() => {
            setToast(prev => ({ ...prev, visible: false }));
        }, 2000);
    };

    // 处理表单提交
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        // 验证必填字段
        if (!formData.url.trim()) {
            showToast('请输入文章链接', 'error');
            return;
        }
        if (!formData.source.trim()) {
            showToast('请输入来源', 'error');
            return;
        }

        setLoading(true);
        try {
            const response = await http.post<MaterialResponse>(
                API_PATH.MATERIAL.CREATE,
                formData as unknown as Record<string, unknown>
            );

            response.onSuccess(() => {
                // 关闭弹窗
                setModalVisible(false);
                // 重置表单
                setFormData({
                    url: '',
                    title: '',
                    source: '',
                    author: '',
                    tags: []
                });
                // 刷新列表
                fetchMaterials();
                // 显示成功提示
                showToast('素材添加成功', 'success');
            }).onError((code, msg) => {
                console.error(`添加失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`添加失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 导航到素材详情页
    const navigateToDetail = (materialId: string) => {
        window.location.href = `/material-detail/${materialId}`;
    };

    return (
        <div className="min-h-screen bg-gray-50">
            {/* 顶部导航栏 */}
            <header className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between items-center h-16">
                        <div className="flex items-center">
                            <button
                                onClick={handleBack}
                                className="inline-flex items-center px-3 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                                </svg>
                                返回首页
                            </button>
                        </div>
                        <h1 className="text-xl font-semibold text-gray-900">素材中心</h1>
                        <div className="flex items-center">
                            <button
                                onClick={() => setModalVisible(true)}
                                className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                                </svg>
                                新增素材
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            {/* 主内容区 */}
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* 筛选和操作区 */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
                    <div className="flex flex-wrap items-center justify-between gap-4">
                        <div className="flex items-center gap-4">
                            <label className="text-gray-700 font-medium">状态筛选:</label>
                            <div className="relative">
                                <select
                                    className="appearance-none bg-white border border-gray-300 rounded-lg pl-4 pr-10 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm text-gray-700 shadow-sm"
                                    value={statusFilter || 'all'}
                                    onChange={handleStatusChange}
                                >
                                    <option value="all">全部</option>
                                    {Object.values(MATERIAL_STATUS).map((value) => (
                                        <option key={value} value={value}>
                                            {statusTextMap[value as MaterialStatus]}
                                        </option>
                                    ))}
                                </select>
                                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                                    </svg>
                                </div>
                            </div>

                            <label className="text-gray-700 font-medium">来源筛选:</label>
                            <div className="relative">
                                <select
                                    className="appearance-none bg-white border border-gray-300 rounded-lg pl-4 pr-10 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm text-gray-700 shadow-sm"
                                    value={sourceFilter || 'all'}
                                    onChange={handleSourceChange}
                                    disabled={sourcesLoading}
                                >
                                    <option value="all">全部</option>
                                    {sourceOptions.map((source) => (
                                        <option key={source} value={source}>
                                            {source}
                                        </option>
                                    ))}
                                </select>
                                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* 素材列表区域 */}
                {loading && materials.length === 0 ? (
                    <div className="flex justify-center items-center py-16">
                        <div className="flex flex-col items-center">
                            <svg className="animate-spin h-10 w-10 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span className="mt-3 text-gray-600 font-medium">加载中...</span>
                        </div>
                    </div>
                ) : materials.length === 0 ? (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
                        <div className="flex flex-col items-center">
                            <svg className="w-16 h-16 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                            </svg>
                            <h3 className="mt-4 text-lg font-medium text-gray-900">暂无素材</h3>
                            <p className="mt-1 text-gray-500">添加一个新素材开始使用吧</p>
                            <button
                                onClick={() => setModalVisible(true)}
                                className="mt-6 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500"
                            >
                                <svg className="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                添加素材
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="grid grid-cols-1 gap-6">
                        {materials.map((material, index) => {
                            // 计算序号
                            const materialNumber = (pagination.current - 1) * pagination.pageSize + index + 1;

                            return (
                                <div
                                    key={material.id}
                                    className="bg-white rounded-lg shadow-sm hover:shadow-md transition-all duration-200 overflow-hidden cursor-pointer relative"
                                    onClick={() => navigateToDetail(material.id)}
                                >
                                    <div className="p-6">
                                        <div className="absolute top-4 right-4 flex space-x-2">
                                            <button
                                                onClick={(e) => handleExtractTopic(material.id, e)}
                                                disabled={extracting === material.id}
                                                className={`inline-flex items-center px-3 py-1.5 rounded-md text-sm font-medium ${extracting === material.id
                                                    ? 'bg-gray-50 text-gray-400 border border-gray-200 cursor-not-allowed'
                                                    : material.topic_extracted
                                                        ? 'bg-emerald-50 text-emerald-600 border border-emerald-200 hover:bg-emerald-100'
                                                        : 'bg-indigo-50 text-indigo-600 border border-indigo-200 hover:bg-indigo-100'
                                                    }`}
                                            >
                                                <svg className={`w-4 h-4 mr-1 ${extracting === material.id ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                                </svg>
                                                {extracting === material.id ? '提取中...' : material.topic_extracted ? '重新提取话题' : '提取话题'}
                                            </button>
                                            <button
                                                onClick={(e) => handleRetry(material.id, e)}
                                                className="inline-flex items-center px-3 py-1.5 rounded-md text-sm font-medium bg-emerald-600 text-white hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors shadow-sm"
                                            >
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                                </svg>
                                                {material.status === MATERIAL_STATUS.PENDING ? '立即爬取' : '重新爬取'}
                                            </button>
                                            <button
                                                onClick={(e) => handleDelete(material.id, e)}
                                                className="inline-flex items-center px-3 py-1.5 rounded-md text-sm font-medium bg-rose-600 text-white hover:bg-rose-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-rose-500 transition-colors shadow-sm"
                                            >
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                                删除
                                            </button>
                                        </div>
                                        <div className="flex items-start justify-between">
                                            <div className="flex-1">
                                                <div className="flex items-center gap-3 mb-2">
                                                    <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium ${statusColorMap[material.status]}`}>
                                                        {statusTextMap[material.status]}
                                                    </span>
                                                    <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-gradient-to-br from-indigo-500 to-indigo-600 text-white font-medium text-sm shadow-sm">
                                                        {materialNumber}
                                                    </span>
                                                </div>
                                                <h3 className="text-lg font-medium text-gray-900 mb-2">
                                                    {material.title || '无标题'}
                                                </h3>
                                                <div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
                                                    <span className="flex items-center">
                                                        <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9.5a2 2 0 00-2-2h-2" />
                                                        </svg>
                                                        {material.source}
                                                    </span>
                                                    <span className="flex items-center">
                                                        <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                        </svg>
                                                        {material.author || '未知作者'}
                                                    </span>
                                                    {material.display_name && (
                                                        <span className="flex items-center">
                                                            <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                                                            </svg>
                                                            上传者：{material.display_name}
                                                        </span>
                                                    )}
                                                </div>
                                                <div className="flex flex-wrap gap-2 mb-3">
                                                    {material.tags?.map((tag, tagIndex) => (
                                                        <span
                                                            key={tagIndex}
                                                            className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800"
                                                        >
                                                            {tag}
                                                        </span>
                                                    ))}
                                                </div>
                                                <div className="flex items-center justify-between text-sm text-gray-500">
                                                    <div className="flex items-center gap-4">
                                                        <span>创建时间：{formatDate(material.created_at)}</span>
                                                        {material.processed_at && (
                                                            <span>处理时间：{formatDate(material.processed_at)}</span>
                                                        )}
                                                    </div>
                                                    <a
                                                        href={material.url}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="inline-flex items-center text-emerald-600 hover:text-emerald-700"
                                                        onClick={(e) => e.stopPropagation()}
                                                    >
                                                        <span>查看原文</span>
                                                        <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                                        </svg>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}

                {/* 分页 */}
                {materials.length > 0 && (
                    <div className="mt-8 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => fetchMaterials(pagination.current - 1)}
                                disabled={pagination.current === 1}
                                className={`px-4 py-2 rounded-lg border text-sm font-medium flex items-center ${pagination.current === 1
                                    ? 'bg-gray-50 text-gray-400 border-gray-200 cursor-not-allowed'
                                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50 transition-colors duration-200'
                                    }`}
                            >
                                <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                                </svg>
                                上一页
                            </button>
                            <span className="px-4 py-2 bg-white border border-gray-300 rounded-lg text-sm text-gray-700">
                                第 {pagination.current} 页，共 {Math.ceil(pagination.total / pagination.pageSize)} 页
                            </span>
                            <button
                                onClick={() => fetchMaterials(pagination.current + 1)}
                                disabled={pagination.current * pagination.pageSize >= pagination.total}
                                className={`px-4 py-2 rounded-lg border text-sm font-medium flex items-center ${pagination.current * pagination.pageSize >= pagination.total
                                    ? 'bg-gray-50 text-gray-400 border-gray-200 cursor-not-allowed'
                                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50 transition-colors duration-200'
                                    }`}
                            >
                                下一页
                                <svg className="w-5 h-5 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                                </svg>
                            </button>
                        </div>
                        <div className="text-sm text-gray-600 font-medium">
                            共 {pagination.total} 条记录
                        </div>
                    </div>
                )}
            </main>

            {/* 新增素材弹窗 */}
            {modalVisible && (
                <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn">
                    <div
                        className="bg-white w-full max-w-lg mx-auto rounded-2xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.25)] transform transition-all max-h-[90vh] flex flex-col overflow-hidden animate-scaleIn"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="px-8 py-6 flex justify-between items-center">
                            <h3 className="text-2xl font-medium text-gray-800">新增素材</h3>
                            <button
                                onClick={() => setModalVisible(false)}
                                className="text-gray-400 hover:text-gray-600 focus:outline-none transition-colors rounded-full hover:bg-gray-100 w-8 h-8 flex items-center justify-center"
                            >
                                <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        <div className="flex-1 overflow-y-auto px-8 py-4">
                            <form onSubmit={handleSubmit} className="space-y-6">
                                {/* 文章链接 */}
                                <div>
                                    <div className="flex items-center mb-2">
                                        <label className="block text-sm font-medium text-gray-700">文章链接</label>
                                        <span className="ml-1 text-rose-500 text-sm">*</span>
                                    </div>
                                    <div className="relative group">
                                        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400 group-focus-within:text-emerald-500 transition-colors" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                                            </svg>
                                        </div>
                                        <input
                                            type="url"
                                            className="block w-full pl-12 pr-4 py-3 bg-white text-gray-700 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all shadow-sm hover:border-gray-400"
                                            placeholder="请输入文章链接"
                                            value={formData.url}
                                            onChange={(e) => setFormData(prev => ({ ...prev, url: e.target.value }))}
                                            required
                                        />
                                    </div>
                                </div>

                                {/* 标题 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">标题</label>
                                    <div className="relative group">
                                        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400 group-focus-within:text-emerald-500 transition-colors" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h16M4 18h7" />
                                            </svg>
                                        </div>
                                        <input
                                            type="text"
                                            className="block w-full pl-12 pr-4 py-3 bg-white text-gray-700 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all shadow-sm hover:border-gray-400"
                                            placeholder="请输入文章标题"
                                            value={formData.title}
                                            onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                                        />
                                    </div>
                                </div>

                                {/* 来源 */}
                                <div>
                                    <div className="flex items-center mb-2">
                                        <label className="block text-sm font-medium text-gray-700">来源</label>
                                        <span className="ml-1 text-rose-500 text-sm">*</span>
                                    </div>
                                    <div className="relative group">
                                        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400 group-focus-within:text-emerald-500 transition-colors" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9.5a2 2 0 00-2-2h-2" />
                                            </svg>
                                        </div>
                                        <select
                                            className="block w-full pl-12 pr-10 py-3 bg-white text-gray-700 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all shadow-sm hover:border-gray-400 appearance-none"
                                            value={formData.source}
                                            onChange={(e) => setFormData(prev => ({ ...prev, source: e.target.value }))}
                                            disabled={sourcesLoading}
                                            required
                                        >
                                            {sourcesLoading ? (
                                                <option value="">加载中...</option>
                                            ) : sourceOptions.length === 0 ? (
                                                <option value="">暂无可选来源</option>
                                            ) : (
                                                sourceOptions.map((source, index) => (
                                                    <option key={index} value={source}>
                                                        {source}
                                                    </option>
                                                ))
                                            )}
                                        </select>
                                        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
                                                <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
                                            </svg>
                                        </div>
                                    </div>
                                </div>

                                {/* 作者 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">作者</label>
                                    <div className="relative group">
                                        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400 group-focus-within:text-emerald-500 transition-colors" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                            </svg>
                                        </div>
                                        <input
                                            type="text"
                                            className="block w-full pl-12 pr-4 py-3 bg-white text-gray-700 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all shadow-sm hover:border-gray-400"
                                            placeholder="请输入作者"
                                            value={formData.author}
                                            onChange={(e) => setFormData(prev => ({ ...prev, author: e.target.value }))}
                                        />
                                    </div>
                                </div>

                                {/* 标签 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">标签</label>
                                    <div className="relative group">
                                        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                            <svg className="h-5 w-5 text-gray-400 group-focus-within:text-emerald-500 transition-colors" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                                            </svg>
                                        </div>
                                        <input
                                            type="text"
                                            className="block w-full pl-12 pr-4 py-3 bg-white text-gray-700 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all shadow-sm hover:border-gray-400"
                                            placeholder="请输入标签，用逗号分隔"
                                            value={formData.tags?.join(', ')}
                                            onChange={(e) => setFormData(prev => ({
                                                ...prev,
                                                tags: e.target.value.split(',').map(tag => tag.trim()).filter(Boolean)
                                            }))}
                                        />
                                    </div>
                                </div>
                            </form>
                        </div>

                        {/* 按钮组 */}
                        <div className="px-8 py-6 border-t border-gray-200">
                            <div className="flex justify-end gap-4">
                                <button
                                    type="button"
                                    onClick={() => setModalVisible(false)}
                                    className="px-6 py-3 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 transition-all shadow-sm"
                                >
                                    取消
                                </button>
                                <button
                                    type="submit"
                                    disabled={loading}
                                    onClick={handleSubmit}
                                    className="px-6 py-3 text-sm font-medium text-white bg-emerald-600 rounded-xl hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md"
                                >
                                    {loading ? '提交中...' : '提交'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* CSS动画 */}
            <style dangerouslySetInnerHTML={{
                __html: `
                    @keyframes fadeIn {
                        from { opacity: 0; }
                        to { opacity: 1; }
                    }
                    @keyframes scaleIn {
                        from { transform: scale(0.95); opacity: 0; }
                        to { transform: scale(1); opacity: 1; }
                    }
                    .animate-fadeIn {
                        animation: fadeIn 0.25s ease-out;
                    }
                    .animate-scaleIn {
                        animation: scaleIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
                    }
                    .animate-scalein {
                        animation: scaleIn 0.25s cubic-bezier(0.175, 0.885, 0.32, 1.275);
                    }
                `
            }} />

            {/* Toast提示 */}
            {toast.visible && (
                <div className="fixed bottom-6 right-6 z-50 animate-scalein">
                    <div className={`rounded-lg shadow-lg py-3 px-4 flex items-center gap-2 ${toast.type === 'success' ? 'bg-emerald-500 text-white' :
                        toast.type === 'error' ? 'bg-rose-500 text-white' :
                            'bg-indigo-500 text-white'
                        }`}>
                        {toast.type === 'success' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'error' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'info' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2h-1V9z" clipRule="evenodd" />
                            </svg>
                        )}
                        <span className="font-medium">{toast.message}</span>
                    </div>
                </div>
            )}

            {/* 提取话题确认弹窗 */}
            {showExtractConfirm && (
                <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn">
                    <div className="bg-white w-full max-w-md mx-auto rounded-xl shadow-lg transform transition-all animate-scaleIn">
                        <div className="p-6">
                            <h3 className="text-lg font-medium text-gray-900 mb-4">确认重新提取</h3>
                            <p className="text-sm text-gray-500 mb-6">
                                该素材已经提取过话题，确定要重新提取吗？
                            </p>
                            <div className="flex justify-end gap-3">
                                <button
                                    onClick={() => setShowExtractConfirm(null)}
                                    className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
                                >
                                    取消
                                </button>
                                <button
                                    onClick={() => doExtractTopic(showExtractConfirm)}
                                    className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 transition-colors"
                                >
                                    确认提取
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default MaterialCenter; 